package com.purang.web.schedule.quartz.core;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;

/**
 * 定时任务服务
 *
 * @author Zheming Liu
 * @version 1.0-RELEASE
 * @since 1.0-RELEASE
 */
@Configuration
@ConditionalOnClass(Scheduler.class)
public class QuartzService {

    private static final String JOB_GROUP = "event_job_group";
    private static final String TRIGGER_GROUP = "event_trigger_group";

    @Autowired
    private Scheduler scheduler;

    /**
     * 创建定时任务
     *
     * @param jobDetailName  定时任务名称
     * @param cronExpression cron表达式
     * @param jobClass       定时任务Class
     */
    public void createScheduleJob(String jobDetailName, String cronExpression, Class<? extends Job> jobClass) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(jobClass)
                .withIdentity("task_" + jobDetailName, JOB_GROUP).storeDurably().requestRecovery().build();
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("task_" + jobDetailName, TRIGGER_GROUP).withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, trigger);
    }
}